#include <iostream>
#include <cassert>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <cstdio>
#include <cstring>
using namespace std;

//父进程读取；子进程写入
int main()
{
    //创建管道文件，打开读写端
    int fds[2];
    int n = pipe(fds);
    assert(n == 0);

    //创建子进程：fork()
    pid_t id = fork();
    assert(id >= 0);
    if(id == 0)
    {
        //子进程关闭读取
        close(fds[0]);
        //子进程通信
        int cnt = 0;
        while(1)
        {
            cnt++;
            const char* s = "我是子进程，我正在给你发消息！";
            char buffer[1024];
            //sizeof 是一个操作符，当操作数是变量是可不加括号，是类型是必须加，如sizeof(int)
            snprintf(buffer, sizeof buffer, "child say: %s[%d][child-id:%d]", s, cnt, getpid());
            write(fds[1], buffer, strlen(buffer));
            //sleep(3);
            // break;
        }
        close(fds[1]);
        exit(0);
    }
    //父进程关闭写入
    close(fds[1]);
    //父进程通信
    while(1)
    {
        char buffer[1024];
        ssize_t s = read(fds[0], buffer, sizeof(buffer)-1);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << "Get message：" << buffer << "| my id:" << getpid() << endl;
            break;
        }
        else if(s == 0)
        {
            cout << "read :" << s << endl;
            break;
        }

        // sleep(3);
    }
    close(fds[0]);
    cout << "父进程关闭读入端" << endl;

    int status = 0;
    n = waitpid(id,&status,0);
    assert(n == id);
    cout <<"pid->"<< n << " : "<< (status & 0x7F) << endl;


    //谁是读取，谁是写入？
    // cout << "fds[0]: " << fds[0] << endl;
    // cout << "fds[1]: " << fds[1] << endl;

    return 0;
}